package keypair

import (
	"api/auth"
	"api/common"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"yunion.io/x/jsonutils"
	"yunion.io/x/onecloud/pkg/mcclient"
	modules "yunion.io/x/onecloud/pkg/mcclient/modules/compute"
)

func KeypairApi() {
	client := mcclient.NewClient("https://api.saltyun.com/api/s/identity/v3", // 注意此地址不带端口
		60,
		false,
		true,
		"",
		"")
	token, err := client.Authenticate("admin", "admin@123", "Default", "system", "Default")
	if err != nil {
		log.Fatal(err)
	}

	s := client.NewSession(context.Background(),
		"region0",
		"",
		"apigateway", // 注意此endpoint类型
		token,
	)

	result, err := modules.Keypairs.List(s, nil)
	if err != nil {
		log.Fatal()
	}
	fmt.Printf("%s", jsonutils.Marshal(result).PrettyString())
}

func KeypairPort() {
	url := "https://api.saltyun.com:30888/keypairs"
	method := "GET"

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	client := &http.Client{Transport: tr}
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		fmt.Println(err)
		return
	}

	token, err := auth.TokenPort("admin", "admin@123")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("token:", token)

	req.Header.Add("X-Auth-Token", token)

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	common.OutputJson(string(body))
}

var url = "https://api.saltyun.com:30888/keypairs"

func search() ([]byte, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}

	client := &http.Client{Transport: tr}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		log.Println("http.NewRequest err:", err)
		return nil, err
	}

	token, err := auth.TokenPort("admin", "admin@123")
	if err != nil {
		log.Println("auth.TokenPort err:", err)
		return nil, err
	}

	//log.Println("token: ", token)

	req.Header.Add("X-Auth-Token", token)

	res, err := client.Do(req)
	if err != nil {
		log.Println("client.Do err", err)
		return nil, err
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Println("io.ReadAll", err)
		return nil, err
	}
	return body, nil
}

type response struct {
	Keypairs []keypair `json:"keypairs"` // 匹配 JSON 中的 keypairs 数组
}

// 定义键值对结构体（只包含需要的字段）
type keypair struct {
	ID   string `json:"id"`   // 映射 id 字段
	Name string `json:"name"` // 映射 name 字段
}

func extractKeypair(body []byte) []keypair {
	var resp response
	if err := json.Unmarshal(body, &resp); err != nil {
		log.Println("json.Unmarshal err:", err)
		return nil
	}

	return resp.Keypairs
}

func OutPut() {

	body, err := search()
	if err != nil {
		log.Println("search err:", err)
		return
	}

	keypairs := extractKeypair(body)
	fmt.Println()
	fmt.Println("Keypair(name:id):")
	for _, v := range keypairs {
		fmt.Printf("%s:%s\n", v.Name, v.ID)
	}
	fmt.Println()
}

func GetID(name string) (string, error) {
	body, err := search()
	if err != nil {
		log.Println("search err:", err)
		return "", err
	}

	keypairs := extractKeypair(body)
	for _, v := range keypairs {
		if v.Name == name {
			return v.ID, nil
		}
	}

	err = fmt.Errorf("% no fund!", name)
	return "", err
}
